package net.oschina.simpleplus;

import java.io.IOException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

import org.apache.zookeeper.KeeperException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import net.oschina.simpleplus.servreg.ZooKeeperServReg;

public class HelloServer {

	private static final Logger logger = LoggerFactory.getLogger(HelloServer.class);

	private static final int DEFAULT_PORT = 50051;

	private Server server = null;

	private ZooKeeperServReg zk;

	private static String getLocalIp() {
		try {
			Enumeration<NetworkInterface> interfaces = null;
			interfaces = NetworkInterface.getNetworkInterfaces();
			while (interfaces.hasMoreElements()) {
				NetworkInterface ni = interfaces.nextElement();
				Enumeration<InetAddress> addresss = ni.getInetAddresses();
				while (addresss.hasMoreElements()) {
					InetAddress nextElement = addresss.nextElement();
					if(nextElement.isLoopbackAddress() || nextElement instanceof Inet6Address){
						continue;
					}
					return nextElement.getHostAddress();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private void start() throws IOException, InterruptedException, KeeperException {
		zk = new ZooKeeperServReg();
		zk.connect("localhost:2181");
		String path = "/grpc/serverList";
		server = ServerBuilder.forPort(DEFAULT_PORT).addService(new GreetingServiceImpl()).build().start();

		logger.info("Server started, listening on {}", DEFAULT_PORT);
		zk.create(path, String.format("%s:%d", getLocalIp(), DEFAULT_PORT).getBytes());

		Runtime.getRuntime().addShutdownHook(new Thread() {
			@Override
			public void run() {
				System.err.println("*** shutting down gRPC server since JVM is shutting down");
				HelloServer.this.stop();
				System.err.println("*** server shut down");
			}
		});
	}

	private void stop() {
		if (server != null) {
			server.shutdown();
		}
	}

	/**
	 * Await termination on the main thread since the grpc library uses daemon
	 * threads.
	 */
	private void blockUntilShutdown() throws InterruptedException {
		if (server != null) {
			server.awaitTermination();
		}
	}

	public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
		final HelloServer server = new HelloServer();
		server.start();
		server.blockUntilShutdown();
	}

}
